package com.open.free.boot.common.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.open.free.boot.common.lang.StringToolUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtils {
    private static final Logger logger = LoggerFactory.getLogger(JWTUtils.class);
    // 过期时间 8h
    public static final long EXPIRE_TIME = 8 * 1 * 60 * 60 * 1000;
    // 颁发者
    private static final String SING_USER_NAME = "open-free-team";
    // API 接口访问token key
    public static final String AUTH_HEADER_KEY = "token";

    /**
     * 生成 jwt token
     *
     * @param claims payload 数据声明
     * @return
     */
    public static String createSingleJwtToken(Map<String, String> claims, Long expireTime, String secret) {

        // 设置私钥加密方式
        Algorithm algorithm = Algorithm.HMAC256(secret);

        long nowMillis = System.currentTimeMillis();// 生成JWT的时间
        Date now = new Date(nowMillis);
        // token有效期
        Date endTime = new Date(nowMillis + expireTime);

        JWTCreator.Builder builder = JWT.create();
        builder.withIssuer(SING_USER_NAME) // 设置签发者
                .withIssuedAt(now) // 设置签发时间
                // .withSubject(subject)
                // //sub(Subject)：代表这个JWT的主体，即它的所有人，这个是一个json格式的字符串，可以存放什么userid，roldid之类的，作为什么用户的唯一标志。
                .withJWTId(claims.get("sessionId").toString()) // 设置jti(JWT
                // ID)：是JWT的唯一标识，根据业务需要，这个可以设置为一个不重复的值，主要用来作为一次性token,从而回避重放攻击。
                .withExpiresAt(endTime); // 设置过期时间

        claims.forEach((key, value) -> {
            builder.withClaim(key, value);
        });
        String jwtToken = builder.sign(algorithm);
        System.out.println("JWT生成-" + jwtToken);

        return jwtToken;
    }

    /**
     * 验证token是否正确
     *
     * @param token
     * @return
     */
    public static boolean verify(String token, String secrct) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secrct);
            JWTVerifier verifier = JWT.require(algorithm).withIssuer(SING_USER_NAME).build();
            DecodedJWT jwt = verifier.verify(token);
            return true;

        } catch (JWTVerificationException e) {
            logger.error("非法token:" + token);
            logger.error(e.getMessage());
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 根据token中存储对象获取对应value
     *
     * @param token
     * @param key
     * @return
     */
    public static String getTokenObjectValue(String token, String key) {
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim(key).asString();

    }

    public static void main(String[] args) {
//        String sessionId = StringToolUtils.getGeneratorUUID();
//        Map<String,String> tokenMap = new HashMap<>();
//        tokenMap.put("userName","admin11");
//        tokenMap.put("sessionId",sessionId);
//        tokenMap.put("userId","1");
////
//   String s1 =createSingleJwtToken(tokenMap,Long.parseLong("14400000"),"fbe84008b4e18e4002aa30983902f11bba82b873c135b508799de3f97727be95");
//        System.out.println(s1);
////      String s1="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJvcGVuLWZyZWUtdGVhbSIsInNlc3Npb25JZCI6ImMxMDA3NWI3NWM3OTRhMWQ4YTU1MDk3YjAxMmVhZTRiIiwiZXhwIjoxNjAwODQ0NjE1LCJ1c2VyTmFtZSI6ImFkbWluMTEiLCJpYXQiOjE2MDA4NDQ2MDEsInVzZXJJZCI6IjEiLCJqdGkiOiJjMTAwNzViNzVjNzk0YTFkOGE1NTA5N2IwMTJlYWU0YiJ9.NJwxpim3OyWh7xh5M1URJPdxuftPy55cEL3-yff98GE";
//        boolean fla2 =  verify(s1,"fbe84008b4e18e4002aa30983902f11bba82b873c135b508799de3f97727be95");

        boolean fla =  verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJvcGVuLWZyZWUtdGVhbSIsInNlc3Npb25JZCI6ImEyYTQ3YTkwNDEyMTRlMjQ5NTk4OWJmM2ZjNmM5YjQ1IiwiZXhwIjoxNjAwODYzNTg4LCJ1c2VyTmFtZSI6ImFkbWluMTEiLCJpYXQiOjE2MDA4NDkxODgsInVzZXJJZCI6IjEiLCJqdGkiOiJhMmE0N2E5MDQxMjE0ZTI0OTU5ODliZjNmYzZjOWI0NSJ9.M0LHkhjKX5gfxMar_3WIOu9Yj7HW4VywbHvFPAoQK7E","fbe84008b4e18e4002aa30983902f11bba82b873c135b508799de3f97727be95");
        System.out.println(fla);
//        System.out.println(fla2);
    }


}
